package com.lwq.imserver.code;

import com.lwq.imserver.service.MessageService;
import com.lwq.imserver.util.RedisUtil;
import com.lwq.imserver.util.SslUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/1/17 16:59
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 读空闲时间(秒)
     */
    public final Duration writeIdle = Duration.ofSeconds(60);

    /**
     * 写接空闲时间(秒)
     */
    public final Duration readIdle = Duration.ofSeconds(65);

    private final ChannelHandler loggingHandler = new LoggingHandler();

    private MessageService messageService;

    private RedisUtil redis;

    public WebSocketChannelInitializer(MessageService messageService, RedisUtil redis) {
        this.messageService = messageService;
        this.redis = redis;
    }

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        ChannelPipeline pipeline = sc.pipeline();
//        SSLContext sslContext = SslUtil.createSSLContext("JKS", "20221.jks", "pzgQo1C0");
//        SSLEngine sslEngine = sslContext.createSSLEngine();
//        sslEngine.setNeedClientAuth(false);
//        sslEngine.setUseClientMode(false);
//        pipeline.addLast("sslHandler", new SslHandler(sslEngine));
        pipeline.addLast("http-codec" , new HttpServerCodec());
        pipeline.addLast("http-chunked" , new ChunkedWriteHandler());
        pipeline.addLast("aggregator" , new HttpObjectAggregator(65536));
        // SSL处理器
//        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
//        pipeline.addLast(new WebMessageDecoder());
//        pipeline.addLast(new WebMessageEncoder());
//        //Http消息编码解码
//        pipeline.addLast("http-codec", new HttpServerCodec());
//        //Http消息组装
//        pipeline.addLast("aggregator", new HttpObjectAggregator(65536*100));
//        //WebSocket通信支持
//        pipeline.addLast("http-chunked", new ChunkedWriteHandler());
        pipeline.addLast(new IdleStateHandler(readIdle.getSeconds(), writeIdle.getSeconds(), 0, TimeUnit.SECONDS));
        pipeline.addLast(loggingHandler);
        // 配置通道处理  来进行业务处理
        pipeline.addLast(new EventChannelHandler(messageService, redis));
    }
}
